package com.alks.function.service.impl;

import com.alks.common.data.thread.UserIdThread;
import com.alks.entity.data.entity.SdDepartment;
import com.alks.entity.data.enums.ResultCodeEnum;
import com.alks.entity.data.response.ResponseInfo;
import com.alks.function.data.dto.SdDepartmentDto;
import com.alks.function.mapper.SdDepartmentMapper;
import com.alks.function.service.SdDepartmentService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;


@Slf4j
@Service
public class SdDepartmentServiceImpl extends ServiceImpl<SdDepartmentMapper, SdDepartment> implements SdDepartmentService {

    @Autowired
    private SdDepartmentMapper sdDepartmentMapper;

    /**
     * 查询所有
     * @return
     */
    @Override
    public ResponseInfo FindAll() {
        String companyId = UserIdThread.get().getCompanyId();
        //获取全部数据
        List<SdDepartment> sdDepartmentList = sdDepartmentMapper.queryAll(companyId);
        //把数据赋值到dto中
        List<SdDepartmentDto> sdDepartmentDtoList = sdDepartmentList.stream().map(sdDepartment -> {
            SdDepartmentDto departmentDto = new SdDepartmentDto();
            BeanUtils.copyProperties(sdDepartment, departmentDto);
            return departmentDto;
        }).collect(Collectors.toList());

        //对节点进行排序
        sdDepartmentDtoList = Optional.ofNullable(sdDepartmentDtoList).map(List::stream).orElseGet(Stream::empty).sorted(Comparator.comparing(SdDepartmentDto::getDeptLevel)).collect(Collectors.toList());

        //排除一级节点 根据父id进行分组 获取所有子节点元素
        Map<String, List<SdDepartmentDto>> collect = sdDepartmentDtoList.stream()
                .filter(Objects::nonNull).filter(s -> s.getParentLevel() != null)
                .collect(Collectors.groupingBy(SdDepartmentDto::getParentLevel));

        //添加子节点元素
        for (SdDepartmentDto data : sdDepartmentDtoList) {
            String deptLevel = data.getDeptLevel();
            List<SdDepartmentDto> list = collect.get(deptLevel);
            data.setChildDepartment(list);
        }

        //过滤获取一级数据
        sdDepartmentDtoList = sdDepartmentDtoList.stream().filter(e -> e.getParentLevel() == null).collect(Collectors.toList());

        return ResponseInfo.ok(sdDepartmentDtoList);

    }

    /**
     * 添加
     * @param sdDepartment
     * @return
     */
    @Override
    public ResponseInfo SaveDepartmentInfo(SdDepartment sdDepartment) {
        String companyId = UserIdThread.get().getCompanyId();
        LambdaQueryWrapper<SdDepartment> Wrapper = new LambdaQueryWrapper<>();
        Wrapper.eq(SdDepartment::getDeptNo,sdDepartment.getDeptNo())
                .eq(SdDepartment::getCompanyId,companyId);
        SdDepartment deptNo = getOne(Wrapper);
        if (deptNo !=null){
            return ResponseInfo.error(ResultCodeEnum.DEPT_NO_IS_EXIST.getMessage(), ResultCodeEnum.DEPT_NO_IS_EXIST.getCode());
        }

        //先查
        LambdaQueryWrapper<SdDepartment> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SdDepartment::getDeptLevel,sdDepartment.getDeptLevel())
                .eq(SdDepartment::getCompanyId,companyId);;
        SdDepartment deptId = getOne(queryWrapper);

        if (deptId==null){
            Integer count = sdDepartmentMapper.queryParentLevelIsNull();
            String dept=(count>=10?String.valueOf(count+1):"0"+(count+1));
            sdDepartment.setDeptLevel(dept);
            sdDepartment.setParentLevel("");
        }else {
            Integer count = sdDepartmentMapper.queryParentLevelAll(sdDepartment.getDeptLevel());
            String dept=(count>=10?String.valueOf(count+1):"0"+(count+1));
            sdDepartment.setParentLevel(sdDepartment.getDeptLevel());
            sdDepartment.setDeptLevel(sdDepartment.getDeptLevel()+dept);
        }
        sdDepartment.setCompanyId(companyId);
        sdDepartmentMapper.saveDept(sdDepartment);

        return ResponseInfo.ok();
    }

    /**
     * 查询单个
     * @param deptNo
     * @return
     */
    @Override
    public ResponseInfo FinDepartmentInfo(String deptNo) {
        return ResponseInfo.ok(sdDepartmentMapper.getOne(deptNo));
    }

    /**
     * 修改
     * @param sdDepartment
     * @return
     */
    @Override
    public ResponseInfo updateWithDepartment(SdDepartment sdDepartment) {
        sdDepartmentMapper.updataDepartment(sdDepartment);
        return ResponseInfo.ok();
    }

    @Override
    public ResponseInfo selectLastCombo(String searchKey) {
        String companyId = UserIdThread.get().getCompanyId();
        return ResponseInfo.ok(sdDepartmentMapper.selectLastCombo(companyId, searchKey));
    }

    @Override
    public ResponseInfo delDepartmentInfo(SdDepartment sdDepartment) {
        String companyId = UserIdThread.get().getCompanyId();
        LambdaQueryWrapper<SdDepartment> Wrapper = new LambdaQueryWrapper<>();
        Wrapper.eq(SdDepartment::getDeptNo,sdDepartment.getDeptNo())
                .eq(SdDepartment::getCompanyId,companyId);
        SdDepartment department = getOne(Wrapper);
        if (department ==null){
            return ResponseInfo.error("无效信息");
        }
        LambdaQueryWrapper<SdDepartment> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SdDepartment::getParentLevel,department.getDeptLevel())
                .eq(SdDepartment::getCompanyId,companyId);
        Integer selectCount = sdDepartmentMapper.selectCount(wrapper);
        if (selectCount>1){
            return ResponseInfo.error("存在子节点,不能删除");
        }
        int count = sdDepartmentMapper.selectByDept(sdDepartment.getDeptNo(), companyId);
        if (count>0){
            return ResponseInfo.error("已被引用,不能删除");
        }
        sdDepartmentMapper.deleteById(sdDepartment.getDeptNo());
        return ResponseInfo.ok();
    }
}

